<template>
  <div>
    <el-dialog
      :title="info.isadd ? '商品添加' : '商品编辑'"
      :visible.sync="info.isshow"
      @closed="closed"
      @opened="opened"
    >
      <!-- opend弹框打开事件 -->
      <el-form :model="user"
        >{{ user }}

        <el-form-item label="一级分类" label-width="120px">
          <el-select v-model="user.first_cateid" @change="changeFirst">
            <el-option
              v-for="item in cateList"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="二级级分类" label-width="120px">
          <el-select v-model="user.second_cateid">
            <el-option
              v-for="item in secondeCatelist"
              :key="item.id"
              :label="item.catename"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" label-width="120px">
          <el-input
            v-model="user.goodsname"
            autocomplete="off"
            value="小米10"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格" label-width="120px">
          <el-input
            v-model="user.price"
            autocomplete="off"
            value="999"
          ></el-input>
        </el-form-item>

        <el-form-item label="市场价格" label-width="120px">
          <el-input
            v-model="user.market_price"
            autocomplete="off"
            value="999"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片" label-width="120px">
          <!-- 封装图片 -->
          <!-- 把组件传递过来的图片数据给user $event代表传递过来的file -->
          <uploadimg @sendimg="user.img = $event" ref="upload"></uploadimg>
        </el-form-item>
        <el-form-item label="商品规格" label-width="120px">
          <el-select v-model="user.specsid" @change="changeSpecs">
            <el-option
              v-for="item in specsList"
              :key="item.id"
              :label="item.specsname"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格属性" label-width="120px">
          <el-select v-model="user.specsattr" multiple>
            <el-option
              v-for="item in attrsList"
              :key="item.id"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否新品" label-width="120px">
          <el-radio v-model="user.isnew" :label="1">是</el-radio>
          <el-radio v-model="user.isnew" :label="2">否</el-radio>
        </el-form-item>
        <el-form-item label="是否新品" label-width="120px">
          <el-radio v-model="user.ishot" :label="1">是</el-radio>
          <el-radio v-model="user.ishot" :label="2">否</el-radio>
        </el-form-item>

        <!-- <el-form-item
          label="规格属性"
          label-width="120px"
          v-for="(item, index) in attrArr"
          :key="index"
        >
          <div class="line">
            <el-input v-model="item.val" autocomplete="off"></el-input>
            <el-button
              type="primary"
              v-if="index == 0"
              @click="attrArr.push({ val: '' })"
              >新增规格属性</el-button
            >
            <el-button type="danger" v-else @click="attrArr.splice(index, 1)"
              >删除</el-button
            >
          </div>
        </el-form-item> -->
        <!-- <el-form-item label="规格属性" label-width="120px">
          <div class="line">
            <el-input v-model="user.catename" autocomplete="off"></el-input>
            <el-button type="danger">删除</el-button>
          </div>
        </el-form-item> -->

        <el-form-item label="状态" label-width="120px">
          <el-switch
            v-model="user.status"
            :active-value="1"
            :inactive-value="2"
          ></el-switch>
        </el-form-item>

        <el-form-item label="评论" label-width="120px">
          <div id="editor"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="add" v-if="info.isadd"
          >确 定添加</el-button
        >
        <el-button type="primary" @click="updata" v-else>确定修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import E from "wangeditor";
import { IndexRoutes } from "../../../router";
import {

  reqcatelist,
  reqgoodsadd,
  reqgoodslist,
  reqgoodsinfo,
  reqgoodsedit,
} from "../../../http/api";
import { errorAlert, successAlert } from "../../../utils//alert";
import path from "path";
import specs from "../../../store/modules/specs";
export default {
  props: ["info"],
  data() {
    return {
      // 菜单列表出数值
      menuList: [],

      //   表单数据
      user: {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: [],
        isnew: "",
        ishot: "",
        status: 2,
      },
      // 二级分类列表
      secondeCatelist: [],

      attrsList: [],
      //  规格属性列表
      // attrArr: [
      //   {
      //     val: "",
      //   },
      //   {
      //     val: "",
      //   },
      // ],
    };
  },
  computed: {
    ...mapGetters(
      // 商品列表数据
      {
        // 请求回来的一级分类列表
        cateList: "cate/list",
        //  规格vuex数据
        specsList: "specs/list",
      }
    ),
  },
  methods: {
    // 分类下的数据请求
    ...mapActions({
      reqCateList: "cate/reqList",
      // 请求规格的列表方法
      reqSpecsList: "specs/reqSpecsList",
      //商品列表
      reqList: "goods/reqList",
    }),
    // 点击取消
    cancel() {
      this.info.isshow = false;
    },
    // 点击一级分类改变
    changeFirst() {
      // 根据一级分类的id请求二级分类
      // 二级分类的值先清空
      this.user.second_cateid = "";
      this.getsecondelist();
    },

    // 计算二级列表
    async getsecondelist() {
      //await 等待成功后执行的结果 就是 reqcatelist({pid:this.user.first_cateid}).then(res=>{

      // console.log(res); }) 及成功状态下后执行的结果
      //根据一级列表id请求二级列表对应参数
      let res = await reqcatelist({ pid: this.user.first_cateid });
      if (res.data.code === 200) {
        // 二级列表请求数据赋值
        this.secondeCatelist = res.data.list ? res.data.list : [];
      }
    },
    // 规格发生改变计算规格属性
    changeSpecs() {
      //每次商品规格的时候吧 规格属性清空一遍 清空选中的属性
      this.user.specsattr = [];
      // 找出每一个specslist列表中的等于this.user.specsid的每一项中的id
      let obj = this.specsList.find((item) => item.id === this.user.specsid);
      //  循环的规格属性的列表specsList等于id相同的attrs
      this.attrsList = obj ? obj.attrs : [];
    },
  

    // 清空user
    empty() {
      this.user = {
        first_cateid: "",
        second_cateid: "",
        goodsname: "",
        price: "",
        market_price: "",
        img: "",
        description: "",
        specsid: "",
        specsattr: "",
        isnew: "",
        ishot: "",
        status: 2,
      };
      // 二级分类列表
      (this.secondeCatelist = []), (this.attrsList = []);
      //  规格属性列表
      // 清空图片
      this.$refs.upload.setImgUrl("");
    
      this.editor.txt.html("")
    },
    // 检查数据
     checkedData() {
      return new Promise((resolve, reject) => {
        // 验证数据是否满足条件
        if (this.user.first_cateid === "") {
          errorAlert("一级分类不能为空");
          return;
        }
        if (this.user.second_cateid === "") {
          errorAlert("二级分类不能为空");
          return;
        }
        if (this.user.goodsname === "") {
          errorAlert("商品名称不能为空");
          return;
        }
        if (this.user.price === "") {
          errorAlert("商品价格不能为空");
          return;
        }
        if (this.user.market_price === "") {
          errorAlert("市场价格不能为空");
          return;
        }
        if (this.user.img === "") {
          errorAlert("图片不能为空");
          return;
        }
        if (this.user.specsid === "") {
          errorAlert("规格不能为空");
          return;
        }
        // if (this.user.specsattr.length >= 0) {
        //   errorAlert("规格属性不能为空");
        //   return;
        // }
        if (this.editor.txt.html() === "") {
          errorAlert("商品描述不能为空");
          return;
        }
        resolve();
      });
    },

    // 添加数据
     add() {
      this.checkedData().then(async()=>{
          // 将attrArr赋值给attr [{val:1},{val:2}] 转成[1,2,3]
      // let data=  [].concat(this.user)
      // 实现深拷贝
         let data = { 
        ...this.user,
        specsattr : JSON.stringify(this.user.specsattr),
        description:this.editor.txt.html()
        }
        console.log(data);
        // 验证数据是否满足条件
       
      // 用json.parse(json.stringify())方法深拷贝会使对象丢失
      // data.specsattr = JSON.stringify(this.user.specsattr);
      // console.log(data)
    // 编辑器的内容给description
   
      //await 等待成功后执行的结果 就是 reqcatelist({pid:this.user.first_cateid}).then(res=>{
      // console.log(res); }) 及成功状态下后执行的结果
      let res = await reqgoodsadd(data);
      if (res.data.code === 200) {
       successAlert(res.data.msg);
        // 清空·user
       console.log(res);
       this.empty();
       this.info.isshow = false;
        刷新列表
        this.reqList();
      }
      })
    
    
     
    },

    getone(id) {
      reqgoodsinfo({ id: id }).then((res) => {
        console.log(res.data.code === 200);
        if (res.data.code == 200) {
          this.user = res.data.list;
          // 补个ID
          this.user.id = id;
          // 根据一级分类id获取二级分类列表
          this.getsecondelist();
          //根据图片赋值
          this.$refs.upload.setImgUrl(this.$pre + this.user.img);

          // 根据规格  计算显示列表
          // 找出每一个specslist列表中的等于this.user.specsid的每一项中的id
          let obj = this.specsList.find(
            (item) => item.id === this.user.specsid
          );
          //  循环的规格属性的列表specsList等于id相同的attrs
          this.attrsList = obj ? obj.attrs : [];

          //  user.specsattr转成数组、
          this.user.specsattr = JSON.parse(this.user.specsattr);
          // 富文本编辑器赋值
          if(this.editor){
               this.editor.text.html(this.user.description)
          }
        
        }
      });
    },
    // 修改
    updata() {
      // 实现深拷贝
      this.checkedData().then(async()=>{
     // let data = { ...this.user };
      // // 用json.parse(json.stringify())方法深拷贝会使对象丢失
      // data.specsattr = JSON.stringify(this.user.specsattr);
         let data = { 
        ...this.user,
        specsattr : JSON.stringify(this.user.specsattr),
        description:this.editor.txt.html()
        }

      reqgoodsedit(data).then((res) => {
        if (res.data.code == 200) {
          successAlert(res.data.msg);

          this.empty();
          this.info.isshow = false;
          // 刷新列表
          this.reqList();
        }
      });
      })
 
    },
    // 弹框消失
    closed() {
      //  input消失
      this.$refs.upload.setshowinput(false);
      // 图片框图片消失
      //  this.$refs.upload.setImgUrl("")
    // 添加取消
     if(this.info.isadd){
      //  将编辑器呃逆荣纯放在user.description
      this.user.description=this.editor.txt.html()
     }

      // 若果是编辑的关闭 就执行empty
      // 不是添加
      if (!this.info.isadd) {
        this.empty();
      }
    },
      // 弹框出现
    opened() {
      //  控制子组件uploadimg中input出现
      this.$refs.upload.setshowinput(true);

      //  创建文本编辑器
      this.editor = new E("#editor");
      this.editor.create();
      // 给编辑器赋值
      this.editor.txt.html(this.user.description)
    },
  },
  mounted() {
    this.reqCateList();
    //  请求规格列表
    this.reqSpecsList(true);
  },
};
</script>
<style lang="less" scoped>
@import "../../../less/index.less";
.line {
  display: flex;
  .el-input {
    flex: 1;
  }
}
</style>